<template>
  <div class="role-list-container">
    <div class="header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAdd">新增角色</el-button>
    </div>

    <div class="search-form">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="roleList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="code" label="角色编码" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 角色表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" :disabled="roleForm.id !== undefined" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="4" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getRolePage, createRole, updateRole, deleteRole } from '@/api/system/role';
import { type Role, type RoleRequest } from '@/types/system/user.ts';
import type { FormInstance } from 'element-plus';

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: ''
});

// 角色列表数据
const roleList = ref<Role[]>([]);
const total = ref(0);
const loading = ref(false);

// 角色表单对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const roleFormRef = ref<FormInstance>();
const roleForm = reactive<RoleRequest>({
  name: '',
  code: '',
  description: ''
});

// 表单校验规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
};

// 获取角色列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getRolePage(queryParams);
    roleList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.error('获取角色列表失败', error);
    ElMessage.error('获取角色列表失败');
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.name = '';
  handleQuery();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;
  getList();
};

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色';
  roleForm.id = undefined;
  roleForm.name = '';
  roleForm.code = '';
  roleForm.description = '';
  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row: Role) => {
  dialogTitle.value = '编辑角色';
  roleForm.id = row.id;
  roleForm.name = row.name;
  roleForm.code = row.code;
  roleForm.description = row.description;
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return;

  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (roleForm.id) {
          await updateRole(roleForm);
          ElMessage.success('更新角色成功');
        } else {
          await createRole(roleForm);
          ElMessage.success('创建角色成功');
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error('提交角色表单失败', error);
        ElMessage.error('提交角色表单失败');
      }
    }
  });
};

// 删除角色
const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 ${row.name} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteRole(row.id);
    ElMessage.success('删除角色成功');
    getList();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除角色失败', error);
      ElMessage.error('删除角色失败');
    }
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.role-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
